import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DetailedGradingFrame extends JFrame {
    private int examId;
    private int studentId;
    private User teacher;
    private Exam exam;
    private ExamRecord examRecord;
    private User student;

    // 数据访问对象
    private ExamDAO examDAO;
    private QuestionDAO questionDAO;
    private AnswerRecordDAO answerRecordDAO;
    private ExamRecordDAO examRecordDAO;
    private UserDAO userDAO;

    // 界面组件
    private JPanel questionsPanel;
    private JScrollPane questionsScrollPane;
    private JLabel totalScoreLabel;
    private JTextField totalScoreField;
    private JButton saveButton;
    private JButton autoCalculateButton;
    private JButton closeButton;

    // 数据存储
    private List<Question> questions;
    private List<AnswerRecord> answerRecords;
    private Map<Integer, JTextField> scoreFields; // questionId -> scoreField
    private Map<Integer, AnswerRecord> answerMap; // questionId -> answerRecord

    public DetailedGradingFrame(int examId, int studentId, User teacher) {
        this.examId = examId;
        this.studentId = studentId;
        this.teacher = teacher;

        // 初始化DAO
        this.examDAO = new ExamDAO();
        this.questionDAO = new QuestionDAO();
        this.answerRecordDAO = new AnswerRecordDAO();
        this.examRecordDAO = new ExamRecordDAO();
        this.userDAO = new UserDAO();

        // 初始化数据存储
        this.scoreFields = new HashMap<>();
        this.answerMap = new HashMap<>();

        // 加载数据
        loadData();

        // 初始化界面
        initComponents();
        setupLayout();
        setupEvents();
        loadAnswerData();
    }

    private void loadData() {
        this.exam = examDAO.getExamById(examId);
        this.student = userDAO.getUserById(studentId);
        this.examRecord = examRecordDAO.getExamRecord(examId, studentId);
        this.questions = questionDAO.getQuestionsByExamId(examId);
        this.answerRecords = answerRecordDAO.getAnswersByExamRecord(examRecord.getId());

        // 创建答案映射
        for (AnswerRecord record : answerRecords) {
            answerMap.put(record.getQuestionId(), record);
        }
    }

    private void initComponents() {
        setTitle("详细阅卷 - " + (exam != null ? exam.getTitle() : "考试"));
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(1200, 800);
        setLocationRelativeTo(null);

        // 创建主要组件
        questionsPanel = new JPanel();
        questionsPanel.setLayout(new BoxLayout(questionsPanel, BoxLayout.Y_AXIS));

        questionsScrollPane = new JScrollPane(questionsPanel);
        questionsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        questionsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        totalScoreLabel = new JLabel("总分:");
        totalScoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        totalScoreField = new JTextField(10);
        totalScoreField.setFont(new Font("微软雅黑", Font.BOLD, 16));
        totalScoreField.setHorizontalAlignment(JTextField.CENTER);
        totalScoreField.setEditable(false);
        totalScoreField.setBackground(new Color(248, 249, 250));
        totalScoreField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(40, 167, 69), 2),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)));

        saveButton = new JButton("保存评分");
        saveButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        saveButton.setBackground(new Color(40, 167, 69));
        saveButton.setForeground(Color.WHITE);

        autoCalculateButton = new JButton("自动计算总分");
        autoCalculateButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        autoCalculateButton.setBackground(new Color(23, 162, 184));
        autoCalculateButton.setForeground(Color.WHITE);

        closeButton = new JButton("关闭");
        closeButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        closeButton.setBackground(new Color(108, 117, 125));
        closeButton.setForeground(Color.WHITE);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));

        // 顶部信息面板
        JPanel topPanel = createTopPanel();

        // 中间题目面板
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "题目详情与评分",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));
        centerPanel.add(questionsScrollPane, BorderLayout.CENTER);

        // 底部操作面板
        JPanel bottomPanel = createBottomPanel();

        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(70, 130, 180));
        panel.setPreferredSize(new Dimension(1200, 80));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        // 标题
        JLabel titleLabel = new JLabel("详细阅卷", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);

        // 信息面板
        JPanel infoPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        infoPanel.setOpaque(false);

        JLabel examLabel = new JLabel("考试: " + (exam != null ? exam.getTitle() : "未知"));
        examLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        examLabel.setForeground(Color.WHITE);

        JLabel studentLabel = new JLabel("学生: " + (student != null ? student.getRealName() : "未知"));
        studentLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        studentLabel.setForeground(Color.WHITE);

        infoPanel.add(examLabel);
        infoPanel.add(studentLabel);

        panel.add(titleLabel, BorderLayout.CENTER);
        panel.add(infoPanel, BorderLayout.EAST);

        return panel;
    }

    private JPanel createBottomPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));

        // 总分面板
        JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        scorePanel.add(totalScoreLabel);
        scorePanel.add(totalScoreField);
        scorePanel.add(autoCalculateButton);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 5));
        buttonPanel.add(saveButton);
        buttonPanel.add(closeButton);

        panel.add(scorePanel, BorderLayout.WEST);
        panel.add(buttonPanel, BorderLayout.EAST);

        return panel;
    }

    private void setupEvents() {
        autoCalculateButton.addActionListener(e -> calculateTotalScore());
        saveButton.addActionListener(e -> saveGrading());
        closeButton.addActionListener(e -> dispose());
    }

    private void loadAnswerData() {
        questionsPanel.removeAll();

        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);
            AnswerRecord answerRecord = answerMap.get(question.getId());

            JPanel questionPanel = createQuestionPanel(question, answerRecord, i + 1);
            questionsPanel.add(questionPanel);

            if (i < questions.size() - 1) {
                questionsPanel.add(Box.createVerticalStrut(10));
            }
        }

        // 自动计算并设置总分
        calculateTotalScore();

        questionsPanel.revalidate();
        questionsPanel.repaint();
    }

    private JPanel createQuestionPanel(Question question, AnswerRecord answerRecord, int questionNumber) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY, 1),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));
        panel.setBackground(Color.WHITE);

        // 题目信息面板
        JPanel questionInfoPanel = createQuestionInfoPanel(question, questionNumber);

        // 学生答案面板
        JPanel answerPanel = createAnswerPanel(question, answerRecord);

        // 评分面板
        JPanel gradingPanel = createGradingPanel(question, answerRecord);

        panel.add(questionInfoPanel, BorderLayout.NORTH);
        panel.add(answerPanel, BorderLayout.CENTER);
        panel.add(gradingPanel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createQuestionInfoPanel(Question question, int questionNumber) {
        JPanel panel = new JPanel(new BorderLayout(10, 5));

        // 题目标题和分数面板
        JPanel titlePanel = new JPanel(new BorderLayout());

        JLabel titleLabel = new JLabel("第" + questionNumber + "题 (" + getQuestionTypeText(question.getQuestionType()) +
                " - 满分" + question.getScore() + "分)");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setForeground(new Color(70, 130, 180));

        titlePanel.add(titleLabel, BorderLayout.WEST);

        // 如果需要人工评分，在右侧添加分数编辑区域
        if (needsManualGrading(question.getQuestionType())) {
            JPanel scoreEditPanel = createScoreEditPanel(question);
            titlePanel.add(scoreEditPanel, BorderLayout.EAST);
        }

        // 题目内容
        JTextArea questionTextArea = new JTextArea(question.getQuestionText());
        questionTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        questionTextArea.setEditable(false);
        questionTextArea.setLineWrap(true);
        questionTextArea.setWrapStyleWord(true);
        questionTextArea.setBackground(new Color(248, 249, 250));
        questionTextArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(titlePanel, BorderLayout.NORTH);
        panel.add(questionTextArea, BorderLayout.CENTER);

        // 如果是选择题，显示选项
        if ("single_choice".equals(question.getQuestionType()) ||
                "multiple_choice".equals(question.getQuestionType())) {
            JPanel optionsPanel = createOptionsPanel(question);
            panel.add(optionsPanel, BorderLayout.SOUTH);
        }

        return panel;
    }

    private JPanel createScoreEditPanel(Question question) {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        panel.setOpaque(false);

        JLabel scoreLabel = new JLabel("得分:");
        scoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        scoreLabel.setForeground(new Color(220, 53, 69));

        // 创建可编辑的分数字段
        JTextField scoreField = new JTextField(6);
        scoreField.setFont(new Font("微软雅黑", Font.BOLD, 14));
        scoreField.setHorizontalAlignment(JTextField.CENTER);
        scoreField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 53, 69), 2),
                BorderFactory.createEmptyBorder(2, 5, 2, 5)));

        // 设置当前分数
        AnswerRecord answerRecord = answerMap.get(question.getId());
        if (answerRecord != null && answerRecord.getScore() >= 0) {
            scoreField.setText(String.valueOf(answerRecord.getScore()));
        } else {
            scoreField.setText("0");
        }

        // 添加输入验证和自动计算
        scoreField.addActionListener(e -> {
            validateAndUpdateScore(question, scoreField);
            calculateTotalScore();
        });

        scoreField.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                validateAndUpdateScore(question, scoreField);
                calculateTotalScore();
            }
        });

        JLabel maxScoreLabel = new JLabel("/" + question.getScore());
        maxScoreLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        maxScoreLabel.setForeground(new Color(108, 117, 125));

        // 保存到映射中
        scoreFields.put(question.getId(), scoreField);

        panel.add(scoreLabel);
        panel.add(scoreField);
        panel.add(maxScoreLabel);

        return panel;
    }

    private void validateAndUpdateScore(Question question, JTextField scoreField) {
        try {
            String text = scoreField.getText().trim();
            if (text.isEmpty()) {
                scoreField.setText("0");
                return;
            }

            double score = Double.parseDouble(text);
            if (score < 0) {
                score = 0;
                scoreField.setText("0");
                JOptionPane.showMessageDialog(this, "分数不能为负数！", "输入错误", JOptionPane.WARNING_MESSAGE);
            } else if (score > question.getScore()) {
                score = question.getScore();
                scoreField.setText(String.valueOf(question.getScore()));
                JOptionPane.showMessageDialog(this, "分数不能超过满分！", "输入错误", JOptionPane.WARNING_MESSAGE);
            }

            // 更新背景色以提示已修改
            scoreField.setBackground(new Color(255, 248, 220));

        } catch (NumberFormatException e) {
            scoreField.setText("0");
            JOptionPane.showMessageDialog(this, "请输入有效的数字！", "输入错误", JOptionPane.WARNING_MESSAGE);
        }
    }

    private JPanel createOptionsPanel(Question question) {
        JPanel panel = new JPanel(new GridLayout(0, 2, 10, 5));
        panel.setBorder(BorderFactory.createTitledBorder("选项:"));

        List<QuestionOption> options = question.getOptions();
        if (options != null) {
            for (QuestionOption option : options) {
                JLabel optionLabel = new JLabel(option.getOptionLabel() + ". " + option.getOptionText());
                optionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
                if (option.isCorrect()) {
                    optionLabel.setForeground(new Color(40, 167, 69));
                    optionLabel.setFont(new Font("微软雅黑", Font.BOLD, 13));
                }
                panel.add(optionLabel);
            }
        }

        return panel;
    }

    private JPanel createAnswerPanel(Question question, AnswerRecord answerRecord) {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                "学生答案",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 14)));

        String answerText = answerRecord != null ? answerRecord.getAnswerText() : "未作答";
        if (answerText == null || answerText.trim().isEmpty()) {
            answerText = "未作答";
        }

        JTextArea answerArea = new JTextArea(answerText);
        answerArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        answerArea.setEditable(false);
        answerArea.setLineWrap(true);
        answerArea.setWrapStyleWord(true);
        answerArea.setBackground(new Color(255, 248, 220));
        answerArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 根据题目类型调整显示高度
        int rows = getAnswerDisplayRows(question.getQuestionType(), answerText);
        answerArea.setRows(rows);

        JScrollPane scrollPane = new JScrollPane(answerArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private int getAnswerDisplayRows(String questionType, String answerText) {
        if ("essay".equals(questionType)) {
            return Math.max(5, Math.min(10, answerText.length() / 50 + 2));
        } else if ("fill_blank".equals(questionType)) {
            return 2;
        } else {
            return 3;
        }
    }

    private JPanel createGradingPanel(Question question, AnswerRecord answerRecord) {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(220, 53, 69)),
                "评分",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 14),
                new Color(220, 53, 69)));

        // 是否需要人工评分
        boolean needsManualGrading = needsManualGrading(question.getQuestionType());

        if (needsManualGrading) {
            // 添加快速评分按钮
            JButton fullScoreButton = new JButton("满分");
            fullScoreButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            fullScoreButton.addActionListener(e -> {
                JTextField scoreField = scoreFields.get(question.getId());
                if (scoreField != null) {
                    scoreField.setText(String.valueOf(question.getScore()));
                    calculateTotalScore(); // 自动计算总分
                }
            });

            JButton halfScoreButton = new JButton("半分");
            halfScoreButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            halfScoreButton.addActionListener(e -> {
                JTextField scoreField = scoreFields.get(question.getId());
                if (scoreField != null) {
                    scoreField.setText(String.valueOf(question.getScore() / 2));
                    calculateTotalScore(); // 自动计算总分
                }
            });

            JButton zeroScoreButton = new JButton("零分");
            zeroScoreButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            zeroScoreButton.addActionListener(e -> {
                JTextField scoreField = scoreFields.get(question.getId());
                if (scoreField != null) {
                    scoreField.setText("0");
                    calculateTotalScore(); // 自动计算总分
                }
            });

            panel.add(new JLabel("快速评分: "));
            panel.add(fullScoreButton);
            panel.add(halfScoreButton);
            panel.add(zeroScoreButton);

        } else {
            // 自动评分
            double autoScore = answerRecord != null ? answerRecord.getScore() : 0;
            JLabel autoScoreLabel = new JLabel("自动评分: " + autoScore + " / " + question.getScore() + " 分");
            autoScoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
            autoScoreLabel.setForeground(new Color(40, 167, 69));

            panel.add(autoScoreLabel);
        }

        return panel;
    }

    private boolean needsManualGrading(String questionType) {
        return "essay".equals(questionType) || "fill_blank".equals(questionType);
    }

    private String getQuestionTypeText(String type) {
        switch (type) {
            case "single_choice":
                return "单选题";
            case "multiple_choice":
                return "多选题";
            case "true_false":
                return "判断题";
            case "fill_blank":
                return "填空题";
            case "essay":
                return "问答题";
            default:
                return type;
        }
    }

    private void calculateTotalScore() {
        double totalScore = 0.0;

        for (Question question : questions) {
            AnswerRecord answerRecord = answerMap.get(question.getId());

            if (needsManualGrading(question.getQuestionType())) {
                // 人工评分的题目
                JTextField scoreField = scoreFields.get(question.getId());
                if (scoreField != null && !scoreField.getText().trim().isEmpty()) {
                    try {
                        double score = Double.parseDouble(scoreField.getText().trim());
                        totalScore += score;
                    } catch (NumberFormatException e) {
                        // 忽略无效输入
                    }
                }
            } else {
                // 自动评分的题目
                if (answerRecord != null) {
                    totalScore += answerRecord.getScore();
                }
            }
        }

        totalScoreField.setText(String.valueOf(totalScore));
    }

    private void saveGrading() {
        System.out.println("=== 开始保存评分 ===");
        try {
            // 验证并保存每个题目的分数
            for (Question question : questions) {
                System.out.println("处理题目 ID: " + question.getId() + ", 类型: " + question.getQuestionType());

                if (needsManualGrading(question.getQuestionType())) {
                    // 人工评分的题目
                    JTextField scoreField = scoreFields.get(question.getId());
                    if (scoreField != null) {
                        String scoreText = scoreField.getText().trim();
                        if (!scoreText.isEmpty()) {
                            double score = Double.parseDouble(scoreText);
                            if (score < 0 || score > question.getScore()) {
                                JOptionPane.showMessageDialog(this,
                                        "第" + question.getQuestionOrder() + "题分数超出范围！\n有效范围：0 - " + question.getScore(),
                                        "分数错误",
                                        JOptionPane.ERROR_MESSAGE);
                                return;
                            }

                            System.out.println("更新人工评分题目分数: questionId=" + question.getId() + ", score=" + score);
                            // 更新答题记录分数
                            boolean updateResult = answerRecordDAO.updateAnswerScore(examRecord.getId(),
                                    question.getId(), score);
                            System.out.println("更新结果: " + updateResult);
                        }
                    }
                } else {
                    // 自动评分的题目 - 确保分数已正确保存
                    AnswerRecord answerRecord = answerMap.get(question.getId());
                    if (answerRecord != null) {
                        System.out.println(
                                "确认自动评分题目分数: questionId=" + question.getId() + ", score=" + answerRecord.getScore());
                        // 重新保存一次以确保数据一致性
                        answerRecordDAO.updateAnswerScore(examRecord.getId(), question.getId(),
                                answerRecord.getScore());
                    }
                }
            }

            // 重新计算并保存总分
            calculateTotalScore();
            String totalScoreText = totalScoreField.getText().trim();
            if (!totalScoreText.isEmpty()) {
                double totalScore = Double.parseDouble(totalScoreText);
                System.out.println("更新总分: " + totalScore);

                // 更新考试记录
                examRecord.setTotalScore(totalScore);
                examRecord.setStatus("graded");
                boolean recordUpdateResult = examRecordDAO.updateExamRecord(examRecord);
                System.out.println("考试记录更新结果: " + recordUpdateResult);
            }

            System.out.println("=== 评分保存完成 ===");
            JOptionPane.showMessageDialog(this, "评分保存成功！", "成功", JOptionPane.INFORMATION_MESSAGE);

        } catch (NumberFormatException e) {
            System.out.println("数字格式错误: " + e.getMessage());
            JOptionPane.showMessageDialog(this, "请输入有效的数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception e) {
            System.out.println("保存评分时发生错误: " + e.getMessage());
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "保存失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}